import requests
from loguru import logger
from work.search_site_list import get_site_id


def get_limits(company_info, matching_account):
    cookies = matching_account['cookies']
    matching_project = get_site_id(company_info=company_info, user=matching_account)
    if matching_project == 0:
        return f"账号: {matching_account['account']} -----> 没有 {company_info['company_name']} 该项目"

    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "baggage": "sentry-environment=production,sentry-public_key=9b4a6569c04148aa9ab275932e8b1961,sentry-trace_id=7456bf1f0a0e41188aa2c72cc7018e97,sentry-sample_rate=0.01,sentry-sampled=false",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": f"https://online.seranking.com/admin.site.rankings.site_id-{matching_project['site_id']}.html?ref=project_select_clicked&login=success",
        "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "sentry-trace": "7456bf1f0a0e41188aa2c72cc7018e97-97f8fe4755e27b8f-0",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
    }
    url = f"https://online.seranking.com/api.projects.site.positions.entrypoint.site_id-{matching_project['site_id']}.html"
    res = requests.get(url, headers=headers, cookies=cookies)
    if res.status_code == 200:
        data = res.json()
        track_max = data["data"]["limits"]["tracking_limits"]["max"]
        track_used = data["data"]["limits"]["tracking_limits"]["used"]

        recheck_max = data["data"]["limits"]["recheck_limits"]["max"]
        recheck_used = data["data"]["limits"]["recheck_limits"]["used"]
        limit_dict = {
        "max_keys": track_max,
        "used_keys": track_used,
        "max_recheck": recheck_max,
        "used_recheck": recheck_used
        }
        return limit_dict
    else:
        logger.error(f"请求关键词失败")
        return 0